<template>
  <div class="project-detail-page">
    <!-- 顶部标题 -->
    <Header />
    <div class="back-page">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-link type="primary" @click="onCancel" icon="DArrowLeft"
          >返回</el-link
        >
        <span>首页 / 我的控制台 / 我参与的项目 / 查看项目详情</span>
      </div>

      <!-- 页面内容 -->
      <div class="content">
        <h2>项目详情</h2>

        <!-- 项目信息 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 6px;
                background: rgb(24, 144, 255);
                height: 20px;
                margin-right: 5px;
              "
            ></div>
            <h3>项目信息</h3>
          </div>

          <el-form :model="projectInfo" label-width="120px">
            <el-row
              :gutter="20"
              class="gradient-box"
              style="
                margin-left: 0;
                box-shadow: 0px 3px 11px 1px rgba(0, 0, 0, 0.25);
                padding-top: 10px;
              "
            >
              <el-col :span="12">
                <el-form-item label="项目编号 :">
                  <span>{{ projectInfo.oaCode }}</span>
                </el-form-item>
                <el-form-item label="项目名称 :">
                  <span>{{ projectInfo.name }}</span>
                </el-form-item>
                <el-form-item label="发布时间 :">
                  <span>{{ projectInfo.createTime }}</span>
                </el-form-item>
                <el-form-item label="征集截止日期 :">
                  <span>{{ projectInfo.applyEndTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目状态 :">
                  <span>{{
                    getDictValue(projectStatusOptions, projectInfo.status)
                  }}</span>
                </el-form-item>
                <el-form-item label="评审日期 :">
                  <span>{{ projectInfo.auditTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </section>
        <!-- 项目评审结果 -->
        <section
          class="section"
          v-if="projectInfo.status == 'project_status_end'"
        >
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 6px;
                background: rgb(24, 144, 255);
                height: 20px;
                margin-right: 5px;
              "
            ></div>
            <h3>项目评审结果</h3>
          </div>
          <div
            class="gradient-box"
            style="
              padding: 30px;
              box-shadow: rgba(0, 0, 0, 0.25) 0px 3px 11px 1px;
            "
          >
            <el-table :data="reviewData" border style="width: 100%">
              <!-- 表格头部 -->
              <el-table-column
                type="index"
                label="序号"
                width="80"
                align="center"
              />
              <el-table-column prop="name" label="报名供应商" align="center" />
              <el-table-column prop="status" label="资质审查" align="center">
                <template #default="scope">
                  <span>{{
                    scope.row.status == "apply_supplier_pass"
                      ? "符合"
                      : "不符合"
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :prop="projectInfo.type == 'project_score' ? 'score' : 'price'"
                :label="projectInfo.type == 'project_score' ? '总分' : '价格'"
                align="center"
              />
              <el-table-column
                prop="score_average"
                label="技术分"
                align="center"
                v-if="isLookScore == 1"
              >
                <template #default="scope">
                  <span>{{
                    getScoreOfType(scope.row.supplierId, "score_average")
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="score_business"
                label="商务分"
                align="center"
                v-if="isLookScore == 1"
              >
                <template #default="scope">
                  <span>{{
                    getScoreOfType(scope.row.supplierId, "score_business")
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="score_price"
                label="价格分"
                align="center"
                v-if="isLookScore == 1"
              >
                <template #default="scope">
                  <span>{{
                    getScoreOfType(scope.row.supplierId, "score_price")
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="price"
                label="总价"
                align="center"
                v-if="isLookScore == 1"
              />
              <el-table-column
                prop="result"
                label="评审结果"
                width="120"
                align="center"
              >
                <template #default="scope">
                  <span>{{
                    scope.row.supplierId == outbidOneId ? "中选" : "未中选"
                  }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </section>
        <!-- 参与资料 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 6px;
                background: rgb(24, 144, 255);
                height: 20px;
                margin-right: 5px;
              "
            ></div>
            <h3>参与资料</h3>
          </div>
          <el-form :model="participantInfo" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报告供应商名称 :">
                  <span>{{ participantInfo.name }}</span>
                </el-form-item>
                <el-form-item label="报名时间 :">
                  <span>{{ participantInfo.applyTime }}</span>
                </el-form-item>
                <el-form-item label="联系人姓名 :">
                  <span>{{ participantInfo.supplierName }}</span>
                </el-form-item>
                <el-form-item label="公司电子邮箱 :">
                  <span>{{ participantInfo.supplierEmail }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商编号 :">
                  <span>{{ participantInfo.supplierCode }}</span>
                </el-form-item>
                <el-form-item label="联系人电话 :">
                  <span>{{ participantInfo.supplierPhone }}</span>
                </el-form-item>
                <el-form-item label="参选人是否为制造商或下属子公司">
                  <el-radio-group v-model="participantInfo.isFactory">
                    <el-radio label="是" value="1" />
                    <el-radio label="否" value="0" />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </section>

        <!-- 文件上传部分 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 6px;
                background: rgb(24, 144, 255);
                height: 20px;
                margin-right: 5px;
              "
            ></div>
            <h3>供应商资质审查文件</h3>
          </div>
          <!-- 文件内容 -->
          <div v-for="file in fileList" :key="file.id" class="file-display">
            <p class="file-description">
              {{ file.textValue || "未知文件描述" }}
            </p>
            <div class="file-info">
              <!-- 使用图标表示 PDF 文件 -->
              <img src="../../assets/PDF.png" style="width: 15%" />
              <span class="file-name">{{
                file.pushValue.split("/").pop()
              }}</span>
            </div>
            <div class="file-actions">
              <el-link type="primary" @click="downloadFile(file)">下载</el-link>
              <el-link type="default" @click="previewFile(file)">预览</el-link>
            </div>
          </div>
          <div class="neverTip" v-if="!fileList.length">暂无数据</div>
        </section>

        <!-- 其他文件 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 6px;
                background: rgb(24, 144, 255);
                height: 20px;
                margin-right: 5px;
              "
            ></div>
            <h3>
              {{
                projectInfo.type == "project_relative_price"
                  ? "供应商报价文件"
                  : "供应商资质参选文件"
              }}
            </h3>
          </div>
          <div class="file-display" v-if="documents">
            <p class="file-description">
              {{
                projectInfo.type == "project_relative_price"
                  ? "供应商报价文件"
                  : "供应商资质参选文件"
              }}
            </p>
            <div class="file-info">
              <!-- 使用图标表示 PDF 文件 -->
              <img
                src="../../assets/PDF.png"
                style="width: 15%"
                v-if="projectInfo.type == 'project_relative_price'"
              />

              <img src="../../assets/zip.png" style="width: 15%" v-else />
              <span class="file-name">{{
                documents?.pushValue?.split("/").pop()
              }}</span>
            </div>
            <div class="file-actions">
              <el-link type="primary" @click="downloadFile(documents)"
                >下载</el-link
              >
            </div>
          </div>
          <div class="neverTip" v-else>暂无数据</div>
        </section>
        <div
          style="display: flex; justify-content: center; align-items: center"
          v-if="
            type == 'participate' &&
            projectInfo.status == 'project_status_announcement'
          "
        >
          <el-button
            type="primary"
            @click="cancelApplyHandler"
            style="margin-top: 20px; width: 300px; height: 42px"
            >撤销报名</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getNoticeInfo } from "@/api/projectNotice";
import {
  applySupplierInfo,
  applySupplierListForProject,
  cancelApply,
} from "@/api/project";
import { useDataStore } from "@/store/index.js"; // 引入 Pinia Store
import { showMessage } from "../../utils/common";
import { ElMessageBox } from "element-plus";

const dataStore = useDataStore(); // 使用 Pinia Store
const projectStatusOptions = computed(() => dataStore.project_status);
const route = useRoute();
const router = useRouter();

const id = computed(() => route.query.id);
const type = computed(() => route.query.type);
const projectId = computed(() => route.query.projectId);
//中选供应商id
const outbidOneId = ref("");
//分数list
const scoreDtoList = ref([]);
const projectInfo = ref({});
//报名id
const applyId = ref("");
const participantInfo = ref({});
// 表格数据
const reviewData = ref([]);
//展示分数详情
const isLookScore = ref("0");

const fileList = ref([]);

const documents = ref("");
//处理文件路径
const generatePreviewUrl = (path) => {
  // 确保路径正确，适配后端服务地址
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  return `${baseUrl}${path}`;
};
//撤销报名
const cancelApplyHandler = () => {
  ElMessageBox.confirm("确定要撤销此报名吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      cancelApply(applyId.value).then((res) => {
        if (res.code == 200) {
          showMessage("撤销报名成功", "success");
          router.push(`/myProject?id=${id.value}&type=${type.value}`);
        } else {
          showMessage("撤销报名失败,请稍后重试", "error");
        }
      });
    })
    .catch(() => {
      // 用户点击了取消按钮后的操作（可选）
      showMessage("已取消操作", "info");
    });
};
const getDictValue = (list, value) => {
  return list.find((item) => item.dictValue == value)?.dictLabel;
};
//下载项目
const downloadFile = async (file) => {
  try {
    // Fetch the file data as a blob
    const response = await fetch(generatePreviewUrl(file.pushValue));
    if (!response.ok) throw new Error("下载失败");

    const blob = await response.blob();
    const url = URL.createObjectURL(blob);

    // Create a temporary link for downloading
    const link = document.createElement("a");
    link.href = url;
    link.download = file.pushValue.split("/").pop(); // Extract file name
    link.click();

    // Revoke the URL after download
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error("下载文件失败：", error);
    previewFile(file);
  }
};
//预览
const previewFile = (file) => {
  const url = generatePreviewUrl(file.pushValue);
  window.open(url, "_blank");
};

//获取分数信息
const getScoreOfType = (id, type) => {
  const scoreObj = scoreDtoList.value.find((item) => item.supplierId == id);
  if (scoreObj) {
    const scoreItem = scoreObj.scoreList.find((item) => item.type == type);
    if (scoreItem) {
      return scoreItem.score;
    }
  }
  return "暂无数据";
};

//获取项目供应商和审核结果
const getApplySupplierListForProject = async () => {
  const res = await applySupplierListForProject({ id: projectId.value });
  if (res.code === 200) {
    reviewData.value = res.data.applysupplierDtoList || [];
    scoreDtoList.value = res.data.scoreDtoList || [];
    outbidOneId.value = res.data.outbidOneId;
    isLookScore.value = res.data.isLookScore;
  }
};
const onCancel = () => {
  if (window.history.length > 1) {
    window.history.back(); // 返回上一页
  } else {
    router.push(`judgeProject?type=${route.query.type}`);
    window.location.reload(); // 刷新当前页面
  }
};
onMounted(async () => {
  //获取项目信息
  const res = await getNoticeInfo(projectId.value);
  projectInfo.value = res.data;
  //获取供应商报名项目上传的文件
  const response = await applySupplierInfo(projectId.value);

  const data =
    response.data.filter((file) => file.supplierId == id.value) || [];
  if (data.length) {
    applyId.value = data[0].id;
    participantInfo.value = data[0];
    if (data[0].valueList && data[0].valueList.length) {
      fileList.value = data[0].valueList.filter(
        (file) => file.type !== "pdf_apply_file"
      );
      documents.value = data[0].valueList.find(
        (file) => file.type === "pdf_apply_file"
      );
    }
  }
  //获取项目评审结果
  if (projectInfo.value.status == "project_status_end") {
    getApplySupplierListForProject();
  }
});
</script>

<style scoped>
.back-page {
  min-height: calc(100vh - 56px);
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat
    center center;
  background-size: cover;
}
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ddd;
}
.header span {
  font-size: 18px;
  font-weight: bold;
  margin-left: 16px;
}
.breadcrumb {
  color: #888;
  font-size: 14px;
  padding: 16px;
  padding-bottom: 0;
  padding-left: 0;
  width: 80%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  span {
    margin-left: 20px;
  }
}
.content {
  padding: 16px;
  padding-top: 0;
  padding-bottom: 50px;
  width: 80%;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.51);
  backdrop-filter: blur(34px);
}
.section {
  margin-bottom: 24px;
  padding: 0 20px;
  max-width: 1000px;
  margin: 0 auto 24px;
}
.file-description {
  font-size: 14px;
  color: #555;
  margin-bottom: 10px;
}
.file-info {
  display: flex;
  flex-direction: column;
}
.file-display {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.file-preview {
  width: 100%;
  max-width: 100px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.file-actions {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}
.file-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
.file-item {
  width: 120px;
  text-align: center;
}
.file-name {
  /* margin-left: 40px;*/
}
.file-item .file-actions {
  margin-top: 8px;
}
.neverTip {
  color: #999;
  font-size: 14px;
  margin: 10px 0 0 10px;
}
</style>
